import { deletePointTask, getPointTaskList } from '@/api'
import { musicIndex } from '@/components/PointSettingFormDialog'
import { ElMessage } from '@/stores/elMessage'
import { i18n } from '@/utils'
import { cloneDeep } from 'lodash'
import { ref, type Ref } from 'vue'

/**
 * 任务点图层实例
 */
export interface TaskEvent {
  name?: string | null
  type?: number | null
  id?: number | null
  gps?: string
  time?: number | null
  cameraAngle?: { x: number; y: number }[] | string[]
  taskArrangement?: {
    music?: { index?: string; name?: string }
    index?: string
    name?: string
  }
}

export const defaultFormData = {
  name: '',
  type: null,
  gps: '',
  time: null,
  cameraAngle: [],
  taskArrangement: {
    music: {}
  }
}

// 表单数据
export const form = ref<TaskEvent>(cloneDeep(defaultFormData))

/**
 * 配置任务点弹窗是否可见
 */
export const pointSettingDialogVisible = ref(false)

export const taskPointVoid = ref<(() => void) | null>(null)

export const pointCoordinates: Ref<string | undefined> = ref('')

export const getList = async () => {
  const res = await getPointTaskList()
  return res.data?.list || []
}

function updateTaskPoint(c: TaskEvent) {
  form.value = Object.assign({}, c)

  if (c.cameraAngle) {
    form.value.cameraAngle = c.cameraAngle.map((item: any) => `${item.x},${item.y}`)
  }

  if (c.taskArrangement) {
    if (c.taskArrangement.music) {
      musicIndex.value = c.taskArrangement.music.index
    } else {
      musicIndex.value = c.taskArrangement.index
    }
  }
}
//处理添加/编辑
export const handleTaskEvent = (c: TaskEvent, callback: () => void) => {
  pointCoordinates.value = c.gps || ''
  pointSettingDialogVisible.value = true
  if (c.id) {
    updateTaskPoint(c)
  }
  taskPointVoid.value = callback
}

//删除
export const deleteTaskEvent = async (id: number) => {
  await deletePointTask(id)
  ElMessage({ type: 'success', message: i18n.global.t('cao-zuo-cheng-gong') })
}
